package com.joe.security.distributed.auth.service;

import com.alibaba.fastjson.JSON;
import com.joe.security.distributed.auth.dao.UserDao;
import com.joe.security.distributed.auth.model.UserDto;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description
 * @Author 高建伟-joe
 * @Date 2023-11-08
 */

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Resource
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // UserDetails userDetail = User.withUsername("zhangsan").password("123").authorities("p1").build();
        // UserDetails userDetail = User.withUsername("zhangsan").password("$2a$10$TmgP1lH29H2QzVHq1sBTtukYiYf6UaaG5y98cyiVaBrfoD8RmBBrC").authorities("p1").build();

        UserDto user = userDao.getUserByUsername(username);
        if (ObjectUtils.isEmpty(user)){
            return null;
        }

        List<String> permissionList = userDao.getPermissionByUserId(user.getId());
        if (CollectionUtils.isEmpty(permissionList)){
            return null;
        }
        String[] permissionArray = new String[permissionList.size()];
        permissionList.toArray(permissionArray);
        String password = user.getPassword();
        user.setPassword(null);
        String principal = JSON.toJSONString(user);
        UserDetails userDetail = User.withUsername(principal).password(password).authorities(permissionArray).build();
        return userDetail;
    }
}
